package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.LoginCode;
import com.itheima.reggie.common.MyContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFiler", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //类路径匹配器支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    public static final String[] URLS = {
            "/employee/login"
            , "/backend/**"
            , "/front/**"
            , "/common/upload"
            , "/common/download"
            , "/user/login"
            , "/user/sendMsg"
            ,"/doc.html"
            ,"/webjars/**"
            ,"/swagger-resources"
            ,"/v2/api-docs"

};
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //判断是否拦截该资源
        String uri = req.getRequestURI();

        log.info(uri);
        //放行的资源
        boolean result = isCheck(uri);
        //访问静态资源和登录页面,放行
        if (result) {
            filterChain.doFilter(req, resp);
            return;
        }
        //访问后台,需要进行登录验证
        //判断是否携带id
        Long empId = (Long) req.getSession().getAttribute(LoginCode.EMP_CHECKID);
        if (empId != null) {
            //说明携带了就放行
            MyContext.setLoginId(empId);
            filterChain.doFilter(req, resp);
            MyContext.remove();
            return;
        }

        //访问前台,需要进行登录验证
        //判断是否携带id
        Long userId = (Long) req.getSession().getAttribute(LoginCode.USER_CHECKID);
        if (userId != null) {
            //说明携带了就放行
            MyContext.setLoginId(userId);
            filterChain.doFilter(req, resp);
            MyContext.remove();
            return;
        }
        //没有登录就让他跳转到登录页面
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    /**
     * 路径匹配检查,本次操作是否要放行
     *
     * @param uri
     * @return
     */
    private boolean isCheck(String uri) {
        for (String url : URLS) {
            boolean result = PATH_MATCHER.match(url, uri);
            if (result) {
                return true;
            }
        }
        return false;
    }
}
